<template>
  <el-dialog :title="`${isEdit ? '编辑' : '新增'}故障`" width="700px" :model-value="modelValue" @close="commEvent.onClose">
    <el-form ref="formRef" :model="formValue" :rules="rules">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所属厂区" prop="factoryId">
            <el-select
              @change="commEvent.getDevices"
              v-model="formValue.factoryId"
              :disabled="isEdit"
              placeholder="请选择所属厂区"
              filterable
            >
              <el-option v-for="(item, index) in factorys" :key="index" :label="item.label" :value="item.value || ''" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属产线" prop="lineId">
            <el-select
              @change="commEvent.getDevices"
              v-model="formValue.lineId"
              :disabled="isEdit"
              placeholder="请选择所属产线"
              filterable
            >
              <el-option v-for="(item, index) in lines" :key="index" :label="item.label" :value="item.value || ''" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属设备" prop="deviceId">
            <el-select v-model="formValue.deviceId" :disabled="isEdit" placeholder="请选择所属设备" filterable>
              <el-option
                v-for="item in devcieOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="停止日期" prop="stopDate">
            <el-date-picker v-model="formValue.stopDate" type="datetime" value-format="YYYY-MM-DD" placeholder="请选择生产日期" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="停止时间" prop="stopTimes">
            <el-input-number
              v-model="formValue.stopTimes"
              :min="0"
              :precision="1"
              controls-position="right"
              placeholder="请输入停止时间"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formValue.remark" type="textarea" :rows="3" placeholder="请输入备注" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="commEvent.onClose">取消</el-button>
      <el-button type="primary" @click="commEvent.onEnter">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, nextTick, PropType, ref, watch } from "vue"
import { ElMessage, FormInstance, FormRules } from "element-plus"
import { EnumProps } from "@/components/ProTable/interface"
import { saveStop } from "@/api/modules/device"
import { SystemSpace } from "@/api/interface/device"
import { deviceIdsBound, deviceList } from "@/api/modules/archive"
const props = defineProps({
  modelValue: Boolean,
  rows: { type: Object as PropType<SystemSpace.stopPage>, default: () => {} },
  factorys: { type: Array as PropType<EnumProps[]>, default: () => [] },
  lines: { type: Array as PropType<EnumProps[]>, default: () => [] },
  devicetTypes: { type: Array as PropType<EnumProps[]>, default: () => [] },
  energyGrades: { type: Array as PropType<EnumProps[]>, default: () => [] }
})
const devices = ref<SystemSpace.DeviceList[]>([]) // 已选择设备信息
const checkDevice = ref<number[]>([]) // 已选择设备信息
const emit = defineEmits(["update:modelValue", "refresh"])
// 参数
const formRef = ref<FormInstance>() // 表单实例
const isEdit = computed(() => Boolean(props.rows?.id)) // 是否是编辑
const devcieOption = computed(() => {
  return devices.value.map(item => ({
    label: item.name,
    value: item.id,
    // disabled: checkDevice.value.includes(item.id)
    disabled: false
  }))
})
// 表单数据
const formValue = ref({
  factoryId: undefined as undefined | number,
  lineId: undefined as undefined | number,
  deviceId: undefined as undefined | number,
  stopDate: "",
  stopTimes: 0,
  remark: ""
})
//  表单校验
const rules: FormRules = {
  factoryId: [{ required: true, message: "请选择所属厂区", trigger: "change" }],
  lineId: [{ required: true, message: "请选择所属产线", trigger: "change" }],
  stopDate: [{ required: true, message: "请选择停止日期", trigger: "change" }],
  stopTimes: [{ required: true, message: "请输入停止时间", trigger: "blur" }]
}
// 事件集合
const commEvent = {
  // 获取设备信息
  getDevices: async () => {
    const { factoryId, lineId } = formValue.value
    if (!factoryId || !lineId) {
      devices.value = []
      return
    }
    const { data } = await deviceList({ factoryId, lineId })
    devices.value = data
  },
  // 关闭弹窗
  onClose: () => {
    emit("update:modelValue", false)
  },
  // 确定
  onEnter: () => {
    if (!formRef.value) return
    formRef.value.validate(async valid => {
      if (!valid) return
      let res: any
      if (props.rows?.id) {
        // params.id = props.rows?.id
        // delete params.factoryId
        // delete params.lineId
        // res = await modifyDevice(params)
      } else {
        res = await saveStop({
          factoryId: Number(formValue.value.factoryId),
          lineId: Number(formValue.value.lineId),
          deviceId: formValue.value.deviceId,
          stopDay: formValue.value.stopDate,
          stopTimes: formValue.value.stopTimes,
          remark: formValue.value.remark
        })
      }
      if (res?.code !== "200") return
      ElMessage.success("操作成功")
      commEvent.onClose()
      emit("refresh")
    })
  }
}
watch(
  () => props.modelValue,
  val => {
    if (val) {
      nextTick(async () => {
        if (!formRef.value) return
        formRef.value.resetFields()
        if (props.rows?.id) {
          const { factoryId, lineId, deviceId, stopDate, stopTimes, remark } = props.rows
          formValue.value = {
            factoryId,
            lineId,
            deviceId,
            stopDate,
            stopTimes,
            remark
          }
        }
        const { data } = await deviceIdsBound()
        checkDevice.value = data
      })
    }
  }
)
</script>

<style lang="scss" scoped></style>
